from django.shortcuts import render, redirect, get_object_or_404
from django.contrib.auth import authenticate, login, logout
from django.contrib.auth.decorators import login_required
from django.contrib import messages
from django.db.models import Avg, Count, Sum, Max, Min
from django.http import JsonResponse
from .models import CarRank, UserProfile
from .forms import UserRegisterForm, UserLoginForm, UserProfileForm, UserUpdateForm, CarRankForm
from django.contrib.auth.models import User
import json

def home(request):
    """首页视图"""
    car_count = CarRank.objects.count()
    brand_count = CarRank.objects.values('brand_name').distinct().count()
    avg_price = CarRank.objects.aggregate(avg_min_price=Avg('min_price'), avg_max_price=Avg('max_price'))
    top_cars = CarRank.objects.order_by('ranks')[:10]
    
    context = {
        'car_count': car_count,
        'brand_count': brand_count,
        'avg_min_price': avg_price['avg_min_price'],
        'avg_max_price': avg_price['avg_max_price'],
        'top_cars': top_cars,
    }
    return render(request, 'car_system/home.html', context)

def register(request):
    """用户注册视图"""
    if request.method == 'POST':
        form = UserRegisterForm(request.POST)
        if form.is_valid():
            user = form.save()
            # 创建用户资料
            UserProfile.objects.create(user=user)
            username = form.cleaned_data.get('username')
            messages.success(request, f'账号 {username} 已创建，请登录！')
            return redirect('login')
    else:
        form = UserRegisterForm()
    return render(request, 'car_system/register.html', {'form': form})

def user_login(request):
    """用户登录视图"""
    if request.method == 'POST':
        form = UserLoginForm(request.POST)
        if form.is_valid():
            username = form.cleaned_data.get('username')
            password = form.cleaned_data.get('password')
            user = authenticate(username=username, password=password)
            if user is not None:
                login(request, user)
                messages.success(request, f'欢迎回来，{username}！')
                return redirect('home')
            else:
                messages.error(request, '用户名或密码错误')
    else:
        form = UserLoginForm()
    return render(request, 'car_system/login.html', {'form': form})

def user_logout(request):
    """用户登出视图"""
    logout(request)
    messages.success(request, '您已成功登出')
    return redirect('login')

@login_required
def profile(request):
    """用户个人资料视图"""
    if request.method == 'POST':
        u_form = UserUpdateForm(request.POST, instance=request.user)
        p_form = UserProfileForm(request.POST, request.FILES, instance=request.user.profile)
        
        if u_form.is_valid() and p_form.is_valid():
            u_form.save()
            p_form.save()
            messages.success(request, '您的个人资料已更新')
            return redirect('profile')
    else:
        u_form = UserUpdateForm(instance=request.user)
        p_form = UserProfileForm(instance=request.user.profile)
    
    context = {
        'u_form': u_form,
        'p_form': p_form
    }
    return render(request, 'car_system/profile.html', context)

@login_required
def car_list(request):
    """汽车列表视图"""
    # 获取筛选参数
    brand = request.GET.get('brand', '')
    min_price = request.GET.get('min_price', '')
    max_price = request.GET.get('max_price', '')
    sort_by = request.GET.get('sort_by', 'ranks')
    
    # 基础查询
    cars = CarRank.objects.all()
    
    # 应用筛选
    if brand:
        cars = cars.filter(brand_name__icontains=brand)
    if min_price:
        cars = cars.filter(min_price__gte=min_price)
    if max_price:
        cars = cars.filter(max_price__lte=max_price)
    
    # 排序
    if sort_by == '-ranks':
        cars = cars.order_by('-ranks')
    elif sort_by == 'min_price':
        cars = cars.order_by('min_price')
    elif sort_by == '-min_price':
        cars = cars.order_by('-min_price')
    elif sort_by == 'count':
        cars = cars.order_by('count')
    elif sort_by == '-count':
        cars = cars.order_by('-count')
    else:
        cars = cars.order_by('ranks')
    
    # 获取所有品牌（用于筛选）
    brands = CarRank.objects.values_list('brand_name', flat=True).distinct()
    
    context = {
        'cars': cars,
        'brands': brands,
        'selected_brand': brand,
        'min_price': min_price,
        'max_price': max_price,
        'sort_by': sort_by,
    }
    return render(request, 'car_system/car_list.html', context)

@login_required
def car_detail(request, series_id):
    """汽车详情视图"""
    car = get_object_or_404(CarRank, series_id=series_id)
    # 获取相同品牌的其他车型
    similar_cars = CarRank.objects.filter(brand_name=car.brand_name).exclude(series_id=series_id)[:5]
    
    context = {
        'car': car,
        'similar_cars': similar_cars,
    }
    return render(request, 'car_system/car_detail.html', context)

@login_required
def car_charts(request):
    """汽车数据图表视图"""
    # 按品牌统计车型数量
    brand_data = list(CarRank.objects.values('brand_name').annotate(count=Count('series_id')).order_by('-count')[:10])
    
    # 按价格区间统计车型数量
    price_ranges = [
        {'min': 0, 'max': 10, 'label': '0-10万'},
        {'min': 10, 'max': 15, 'label': '10-15万'},
        {'min': 15, 'max': 20, 'label': '15-20万'},
        {'min': 20, 'max': 30, 'label': '20-30万'},
        {'min': 30, 'max': 50, 'label': '30-50万'},
        {'min': 50, 'max': 100, 'label': '50-100万'},
        {'min': 100, 'max': 1000, 'label': '100万以上'},
    ]
    
    price_data = []
    for pr in price_ranges:
        count = CarRank.objects.filter(min_price__gte=pr['min'], min_price__lt=pr['max']).count()
        price_data.append({'label': pr['label'], 'count': count})
    
    # 按销量区间统计车型数量
    sales_data = list(CarRank.objects.order_by('-count')[:10].values('series_name', 'count'))
    
    context = {
        'brand_data_json': json.dumps(brand_data),
        'price_data_json': json.dumps(price_data),
        'sales_data_json': json.dumps(sales_data),
    }
    return render(request, 'car_system/charts.html', context)

@login_required
def edit_car(request, series_id=None):
    """编辑或添加汽车信息"""
    if series_id:
        car = get_object_or_404(CarRank, series_id=series_id)
        title = '编辑车型信息'
    else:
        car = None
        title = '添加新车型'
    
    if request.method == 'POST':
        form = CarRankForm(request.POST, instance=car)
        if form.is_valid():
            form.save()
            messages.success(request, f'车型信息已{"更新" if series_id else "添加"}')
            return redirect('car_list')
    else:
        form = CarRankForm(instance=car)
    
    return render(request, 'car_system/edit_car.html', {'form': form, 'title': title})

@login_required
def delete_car(request, series_id):
    """删除汽车信息"""
    car = get_object_or_404(CarRank, series_id=series_id)
    if request.method == 'POST':
        car.delete()
        messages.success(request, '车型信息已删除')
        return redirect('car_list')
    return render(request, 'car_system/delete_car.html', {'car': car})

# API视图
def api_car_data(request):
    """返回汽车数据的API视图（用于AJAX请求）"""
    brand = request.GET.get('brand', '')
    cars = CarRank.objects.all()
    if brand:
        cars = cars.filter(brand_name=brand)
    
    data = list(cars.values())
    return JsonResponse({'cars': data})

@login_required
def admin_dashboard(request):
    """管理员仪表盘"""
    # 检查是否为超级用户
    if not request.user.is_superuser:
        messages.error(request, '您无权访问管理页面')
        return redirect('home')
    
    # 获取系统统计信息
    user_count = User.objects.count()
    car_count = CarRank.objects.count()
    brand_count = CarRank.objects.values('brand_name').distinct().count()
    
    # 获取用户列表
    users = User.objects.all().order_by('-date_joined')
    
    context = {
        'user_count': user_count,
        'car_count': car_count,
        'brand_count': brand_count,
        'users': users,
    }
    return render(request, 'car_system/admin_dashboard.html', context)

@login_required
def admin_user_edit(request, user_id):
    """管理员编辑用户信息"""
    # 检查是否为超级用户
    if not request.user.is_superuser:
        messages.error(request, '您无权访问管理页面')
        return redirect('home')
    
    user = get_object_or_404(User, id=user_id)
    
    if request.method == 'POST':
        u_form = UserUpdateForm(request.POST, instance=user)
        # 获取或创建用户资料
        profile, created = UserProfile.objects.get_or_create(user=user)
        p_form = UserProfileForm(request.POST, request.FILES, instance=profile)
        
        if u_form.is_valid() and p_form.is_valid():
            u_form.save()
            p_form.save()
            
            # 处理用户权限
            is_staff = request.POST.get('is_staff') == 'on'
            is_superuser = request.POST.get('is_superuser') == 'on'
            is_active = request.POST.get('is_active') == 'on'
            
            user.is_staff = is_staff
            user.is_superuser = is_superuser
            user.is_active = is_active
            user.save()
            
            messages.success(request, f'用户 {user.username} 的信息已更新')
            return redirect('admin_dashboard')
    else:
        u_form = UserUpdateForm(instance=user)
        # 获取或创建用户资料
        profile, created = UserProfile.objects.get_or_create(user=user)
        p_form = UserProfileForm(instance=profile)
    
    context = {
        'user_obj': user,
        'u_form': u_form,
        'p_form': p_form
    }
    return render(request, 'car_system/admin_user_edit.html', context)

@login_required
def admin_user_delete(request, user_id):
    """管理员删除用户"""
    # 检查是否为超级用户
    if not request.user.is_superuser:
        messages.error(request, '您无权访问管理页面')
        return redirect('home')
    
    user = get_object_or_404(User, id=user_id)
    
    # 防止删除自己
    if user == request.user:
        messages.error(request, '您不能删除自己的账号')
        return redirect('admin_dashboard')
    
    if request.method == 'POST':
        username = user.username
        user.delete()
        messages.success(request, f'用户 {username} 已被删除')
        return redirect('admin_dashboard')
    
    return render(request, 'car_system/admin_user_delete.html', {'user_obj': user})
